package demo.controller;

import cn.hutool.captcha.LineCaptcha;
import demo.model.CaptchaYml;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {

    private final static long session_valid_timeout = 60*1000;
    @Autowired
    private CaptchaYml captchaYml;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = new LineCaptcha(captchaYml.getWidth(), captchaYml.getHeight());
        response.setContentType("image/jpeg");
        response.setHeader("Program", "No-cache");
        lineCaptcha.write(response.getOutputStream());
        session.setAttribute(captchaYml.getSession().getKey(), lineCaptcha.getCode());
        session.setAttribute(captchaYml.getSession().getDate(), new Date());
        response.getOutputStream().close();
    }

    @RequestMapping("/check")
    public Boolean check(HttpSession session, String inputCode){
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }

        String savedCode = (String) session.getAttribute(captchaYml.getSession().getKey());
        Date savedDate = (Date) session.getAttribute(captchaYml.getSession().getDate());

        if(inputCode.equals(savedCode)){
            if(savedCode != null && System.currentTimeMillis() - savedDate.getTime() < session_valid_timeout){
                return true;
            }
        }
        return false;
    }
}
